package felix.rule.js.script;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import felix.rule.js.util.ListeningExecutor;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

@Component
public class JsExecutorServiceImpl implements ListeningExecutor {

    @Setter
    private ListeningExecutorService service;

    @Value("${js.executor_thread_pool_size:10}")
    private int jsExecutorThreadPoolSize;

    @PostConstruct
    public void init() {
        this.service = MoreExecutors.listeningDecorator(Executors.newWorkStealingPool(jsExecutorThreadPoolSize));
    }

    @PreDestroy
    public void destroy() {
        if (this.service != null) {
            this.service.shutdown();
        }
    }

    @Override
    public <T> ListenableFuture<T> executeAsync(Callable<T> task) {
        return service.submit(task);
    }

    @Override
    public void execute(Runnable command) {
        if (service != null) {
            service.execute(command);
        }
    }
}
